package com.vol.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.vol.entity.SysRole;
import com.vol.entity.UserInfo;
import com.vol.mapper.SysRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class RolesUtils {

    @Autowired
    private SysRoleMapper sysRoleMapper;
    private List<Integer> roIdList = new ArrayList<>();
    @Autowired
    private UserContext userContext;

    //获取当前角色和其所有下属角色 - 转换为字符串以，分开返回
    public String getAllChildRolesToStringIds() {
        List<Integer> listRoldIds = this.getAllChildRoles();
        String result = String.join(", ", listRoldIds.toString().replaceAll("\\[|\\]", ""));
        return result;
    }

    //获取当前角色和其所有下属角色
    public List<Integer> getAllChildRoles() {
        UserInfo userInfo = userContext.getUserInfo();
        int RoleId = userInfo.getRole_Id();
        roIdList.clear();
        roIdList.add(RoleId);
        LambdaQueryWrapper<SysRole> qw = new LambdaQueryWrapper<>();
        qw.eq(SysRole::getRoleId, RoleId);
        SysRole sysRole = sysRoleMapper.selectOne(qw);
        if (sysRole != null) {
            this.getChildRoles(sysRole);
        }
        return roIdList;
    }

    //递归查询所有下属角色id
    private void getChildRoles(SysRole sysRole) {
        LambdaQueryWrapper<SysRole> qw = new LambdaQueryWrapper<>();
        qw.eq(SysRole::getParentid, sysRole.getRoleId());
        List<SysRole> list = sysRoleMapper.selectList(qw);
        if (!list.isEmpty()) {
            for (SysRole sysRole1 : list) {
                roIdList.add(sysRole1.getRoleId());
                this.getChildRoles(sysRole1);
            }
        }
    }
}
